package zt

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	`math`
	"math/big"
	"net"
	"strings"
	"time"
	"unicode"
)

// Ip2int64
// Description ip 字符串转int64
// author: sagit
// date: 2022/2/10 21:03
// params:
// return:
func Ip2int64(ipStr string) int64 {
	ret := big.NewInt(0)
	ip := net.ParseIP(ipStr).To4()
	if ip == nil {
		return 0
	}
	ret.SetBytes(ip)
	return ret.Int64()
}

// Ip2Str
// Description ip int64转字符串
// author: sagit
// date: 2022/2/10 21:14
// params:
// return:
func Ip2Str(ip int64) string {
	return fmt.Sprintf("%d.%d.%d.%d", byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

// Timestamp
// Description 获取时间戳
//
// 不传参数则取当前时间戳
// 传入多个时间只返回第一个
//
// 传入时间字符串格式 2006-01-02 15:04:05 或 2006.01.02 15:04:05 或 2006年01月02日 15:04:05
//
// author: sagit
//
// date: 2022/2/10 22:34
// params:
// return:
func Timestamp(date ...string) int64 {
	if len(date) == 0 {
		return time.Now().Unix()
	} else {
		r := strings.NewReplacer(".", "-", "年", "-", "月", "-", "日", "")
		date1 := r.Replace(date[0])
		loc, _ := time.LoadLocation("Local")
		theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", date1, loc)
		return theTime.Unix()
	}
}

// Md5
// Description 计算md5值
// author: sagit
// date: 2022/2/10 23:11
// params:
// return:
func Md5(text string, isUpper ...bool) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	if len(isUpper) == 0 {
		return hex.EncodeToString(ctx.Sum(nil))
	}
	if isUpper[0] {
		return strings.ToUpper(hex.EncodeToString(ctx.Sum(nil)))
	}
	return hex.EncodeToString(ctx.Sum(nil))

}

// UpperFirst
// Description 首字母大写
// author: sagit
// date: 2022/2/11 0:05
// params:
// return:
func UpperFirst(str string) string {
	var upperStr string
	vv := []rune(str)
	for i := 0; i < len(vv); i++ {
		if i == 0 {
			if unicode.IsLower(vv[i]) {
				vv[i] -= 32
				upperStr += string(vv[i])
			} else {
				//fmt.Println("Not begins with lowercase letter,")
				return str
			}
		} else {
			upperStr += string(vv[i])
		}
	}
	return upperStr
}

// UpperWordFirst
// Description 大驼峰
//
// author: sagit
//
// date: 2022/2/11 0:05
// params:
// return:
func UpperWordFirst(str string) string {
	return strings.Title(strings.ToLower(str))
}


var chars string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

func Num10To62(num int64) string {
	bytes := []byte{}
	for num > 0 {
		bytes = append(bytes, chars[num%62])
		num = num / 62
	}
	for left, right := 0, len(bytes)-1; left < right; left, right = left+1, right-1 {
		bytes[left], bytes[right] = bytes[right], bytes[left]
	}
	return string(bytes)
}

func Num62To10(str string) int64 {
	var num int64
	n := len(str)
	for i := 0; i < n; i++ {
		pos := strings.IndexByte(chars, str[i])
		num += int64(math.Pow(62, float64(n-i-1)) * float64(pos))
	}
	return num
}